#!/usr/bin/env python3

import sys
import os
import time

import serial
import serial.tools.list_ports


class SerialSender:
  def __init__(self, port, baudrate=9600):
    self.ser = serial.Serial(port, baudrate)

  def send_data(self, data):
    try:
    # 将数据转换为十六进制字符串并发送
      hex_data = ' '.join(format(val, '02X') for val in data)
      self.ser.write(bytes.fromhex(hex_data))
      print(f"Sent data in hex: {hex_data}")
    except Exception as e:
      print(f"Error during sending data: {e}")

  def close_serial(self):
    self.ser.close()
   
   #发送小车电机驱动的函数
  def air_speed(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
  
  def air_GPS(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])
    
  def air_update_angle(self,array):
    for i in array:
      time.sleep(0)
      self.send_data([i])

  # 接收一个字节(0-255)
  def receive_integer(self):
    try:
      if self.ser.in_waiting > 0:
        # 读取一个字节的数据
        received_byte = self.ser.read(1)
        if received_byte:
          # 将接收到的字节转换为整数
          received_integer = int.from_bytes(received_byte, byteorder='big')
          print(f"Received integer: {received_integer}")
          return received_integer
        else:
          print("No data received.")
          return None
    except Exception as e:
        print(f"Error during receiving data: {e}")
        return None
    
  #接收两个字节（0-360）
  def receive_data(self):
      while True:
          # 读取第一个字节 (十位数)
          shi = self.ser.read(1)  # 读取一个字节
          if shi:
              shi = ord(shi)  # 转换字节为整数
              print(f"Received shi: {shi}")
  
          # 读取第二个字节 (个位数)
          ge = self.ser.read(1)  # 读取一个字节
          if ge:
              ge = ord(ge)  # 转换字节为整数
              print(f"Received ge: {ge}")
  
          # 组合十位和个位数
          number = shi * 10 + ge
          return number

